﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.IO;
using System.Text;

namespace Best.Framework.Web
{
    /// <summary>
    /// 页面基类
    /// </summary>
    public class PageBase : System.Web.UI.Page
    {
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="sourceFilePath">源文件路径</param>
        /// <param name="saveType">开发方式 Attachment下载  Inline浏览器中打开</param>
        protected void FileDownload(string sourceFilePath, SaveType saveType)
        {
            if (string.IsNullOrEmpty(sourceFilePath))
            {
                throw new ArgumentNullException("参数 sourceFilePath 不能为空");
            }
            if (!File.Exists(sourceFilePath))
            {
                throw new FileNotFoundException("目标文件不存在");
            }
            string fileName = sourceFilePath.Substring(sourceFilePath.LastIndexOf('\\') + 1);

            byte[] fileBytes = File.ReadAllBytes(sourceFilePath);
            Response.AddHeader("Content-Disposition", 
                string.Format("{0};filename={1}",saveType, HttpUtility.UrlEncode(fileName, Encoding.UTF8)));
            Response.AddHeader("Content-Length", fileBytes.Length.ToString());
            Response.ContentType = "application/octet-stream";
            //Response.ContentType = "application/msword";
            Response.Charset = "GB2312";
            Response.BinaryWrite(fileBytes);
            Response.Flush();
            Response.End();
        }
    }

    public class SaveType
    {
        /// <summary>
        /// 下载
        /// </summary>
        public static readonly SaveType Attachment = new SaveType(0);

        /// <summary>
        /// 浏览器中打开
        /// </summary>
        public static readonly SaveType Inline = new SaveType(1);

        private int _type;

        private SaveType(int type)
        {
            _type = type;
        }

        public int Type
        {
            get {
                return _type;
            }
        }

        public override string ToString()
        {
            string fmtString = string.Empty;
            switch (_type)
            { 
                case 1:
                    fmtString = "inline";
                    break;
                case 0:
                default:
                    fmtString = "attachment";
                    break;

            }
            return fmtString;
        }
    }
}